package com.wswy.wzcx.ui.njdb

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.constraint.ConstraintSet
import android.text.TextUtils
import android.view.View
import android.widget.Space
import com.blankj.utilcode.util.SizeUtils
import com.che.libcommon.utils.IntentUtils
import com.che.libcommon.utils.ToastUtils
import com.wswy.wzcx.R
import com.wswy.wzcx.model.license.UserCarInfo
import com.wswy.wzcx.model.wzdb.AddUserCertEntry
import com.wswy.wzcx.module.base.CBaseFragment
import com.wswy.wzcx.module.base.getColor
import com.wswy.wzcx.module.base.onClick
import com.wswy.wzcx.ui.Constants
import com.wswy.wzcx.ui.activity.ModuleActivity
import com.wswy.wzcx.ui.data.Certs
import com.wswy.wzcx.ui.other.ClickUtils
import com.wswy.wzcx.ui.wzdb.CertCardSelectView
import com.wswy.wzcx.ui.wzdb.ChooseCertDialog
import com.wswy.wzcx.ui.wzdb.IInputView
import com.wswy.wzcx.utils.FileUtils
import com.wzcx.orclib.PhotoAgent
import kotlinx.android.synthetic.main.fragment_njdb_upload.*
import timber.log.Timber
import java.io.File

/**
 * 上传资料
 */
@Deprecated("")
class NjdbUploadFragment : CBaseFragment(), View.OnClickListener {


    companion object {
        const val TAG = "_NjdbUploadFragment"

        private const val REQ_PICK_GALLERY = 310

        private const val IMG_NAME = "img_njdb_"

        private const val ID_CARD_NAME = "njdb/%d/${IMG_NAME}%s.jpg"


        @JvmStatic
        fun newInstance(bundle: Bundle): NjdbUploadFragment {

            return NjdbUploadFragment().apply {
                arguments = bundle

            }
        }


    }

    override fun getContentLayoutId(): Int {
        return R.layout.fragment_njdb_upload
    }

    override fun getFragmentTitle(): String {
        return "上传资料"
    }


    private val deg = mutableMapOf<Int, Pair<CertCardSelectView, (Int, CertCardSelectView) -> Unit>>()

    private var currPath: String? = null
    private var currId: Int = 0

    private lateinit var userCarInfo: UserCarInfo

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        val carInfo = arguments?.getParcelable<UserCarInfo?>(Constants.EXTRA_DATA)

        if (carInfo == null) {
            finish()
            return
        }

        userCarInfo = carInfo

        view_num_1.background = NumDrawable(1.toString(), getColor(R.color.colorPrimary))
        view_num_2.background = NumDrawable(2.toString(), getColor(R.color.color_normal_hint))
        view_num_3.background = NumDrawable(3.toString(), getColor(R.color.color_normal_hint))
        view_num_4.background = NumDrawable(4.toString(), getColor(R.color.color_normal_hint))

        addPhotos()


        tv_submit.onClick { view ->

            //检测文件
            extraFiles()?.let {

                //选择好文件 去支付
                ModuleActivity.getTargetIntent(view.context, NjdbPreOrderFragment.TAG, Bundle().apply {

                    putParcelable(Constants.EXTRA_DATA, userCarInfo)
                }).let {
                    startActivity(it)

                    finish()

                }

            }


        }

    }


    private fun extraFiles(): Map<String, Any>? {

        val datas = mutableMapOf<String, Any>()
        for (i in 0 until layout_imgs.childCount) {
            val childAt = layout_imgs.getChildAt(i)

            if (childAt is IInputView) {
                if (childAt.value == null || TextUtils.isEmpty(childAt.value?.toString())) {
                    ToastUtils.showText("请选择${childAt.info?.label}")
                    return null
                }

                childAt.info?.key?.let {
                    datas[it] = childAt.value
                }
            }
        }
        return datas
    }

    override fun onClick(v: View?) {

        if (ClickUtils.isFastClick()) {
            return
        }

        currPath = null
        v?.let { view ->

            val context = requireContext()

            val dialog = ChooseCertDialog(context, deg[view.id]?.first?.certEntry?.alias)
            dialog.onChooseListener = object : ChooseCertDialog.OnChooseListener {
                override fun onStartCamera() {

                    val pos = view.id
                    currPath = ID_CARD_NAME.format(userCarInfo.id, dialog.key)
                    FileUtils.getSaveFile(context, currPath)?.let {

                        startPhoto(pos, it.absolutePath, dialog.key)
                    }

                }

                override fun onStartGallery() {

                    currId = view.id
                    //startGallery(view.id)


                    val pos = view.id
                    currPath = ID_CARD_NAME.format(userCarInfo.id, dialog.key)
                    FileUtils.getSaveFile(context, currPath)?.let {

                        startGallery(pos, it.absolutePath, dialog.key)
                    }

                }

            }

            dialog.show()


        }

    }

    private fun addPhotos() {

        //显示上传
        val photos = ArrayList<AddUserCertEntry>()
        photos.add(AddUserCertEntry("P", "行驶证正本正面照片"))
        photos.add(AddUserCertEntry("Q", "行驶证副本正面照片"))
        photos.add(AddUserCertEntry("Z1", "交强险照片"))


        val layout = layout_imgs

        val context = requireContext()


        val keyLocalFile = NjdbUtils.getImgFiles(context, userCarInfo.id)



        Timber.e("files -->>> ${keyLocalFile}")

        val imgIdStart = 17200

        val space = Space(context)
        val spaceId = imgIdStart - 100
        space.id = spaceId


        layout.addView(space, SizeUtils.dp2px(15.toFloat()), SizeUtils.dp2px(15.toFloat()))

        var constraintSet = ConstraintSet()
        constraintSet.clone(layout)

        constraintSet.centerHorizontally(space.id, ConstraintSet.PARENT_ID)
        constraintSet.applyTo(layout)

        val topM = SizeUtils.dp2px(20.toFloat())
        var idN = imgIdStart
        var aboveID = 0
        var leftID = 0
        photos.forEach {

            val view = CertCardSelectView(context)
            view.id = idN
            view.bindEntry(0, it)

            layout.addView(view, 0, 0)

            //填充本地图片
            if (it.key != null) {
                keyLocalFile[it.key!!]?.absolutePath?.let { path ->
                    view.imgPath = path
                }
            }


            constraintSet = ConstraintSet()
            constraintSet.clone(layout)

            view.setOnClickListener(this)
            deg[view.id] = Pair(view, handlePhoto)

            constraintSet.setDimensionRatio(view.id, "4:3")
            if (idN % 2 == 0) {

                constraintSet.connect(view.id, ConstraintSet.LEFT, ConstraintSet.PARENT_ID, ConstraintSet.LEFT)
                constraintSet.connect(view.id, ConstraintSet.RIGHT, space.id, ConstraintSet.LEFT)

                if (aboveID > 0) {
                    constraintSet.connect(view.id, ConstraintSet.TOP, aboveID, ConstraintSet.BOTTOM)
                }

                constraintSet.setMargin(view.id, ConstraintSet.TOP, topM)


                aboveID = idN
                leftID = idN
            } else {
                constraintSet.connect(view.id, ConstraintSet.LEFT, space.id, ConstraintSet.RIGHT)
                constraintSet.connect(view.id, ConstraintSet.RIGHT, ConstraintSet.PARENT_ID, ConstraintSet.RIGHT)

                constraintSet.connect(view.id, ConstraintSet.TOP, leftID, ConstraintSet.TOP)

            }

            constraintSet.applyTo(layout)

            idN++

        }


    }


    private val handlePhoto = fun(id: Int, view: CertCardSelectView) {


        var saveFile = if (TextUtils.isEmpty(currPath)) null else File(currPath)

        if (saveFile == null || !saveFile.exists()) {
            saveFile = FileUtils.getSaveFile(view.context, currPath)
        }


        saveFile?.let {

            if (it.exists()) {
                view.imgPath = it.absolutePath
            }

        }

    }


    private fun startPhoto(id: Int, path: String, key: String?) {

        val intent = PhotoAgent.getPhotoIntent(requireContext(), path, Certs.photoHints[key])

        startActivityForResult(intent, id)
    }

    private fun startGallery(id: Int, path: String, key: String?) {

        //startActivityForResult(IntentUtils.getPickGallery(), REQ_PICK_GALLERY)

        val intent = PhotoAgent.getPhotoIntent(requireContext(), path, Certs.photoHints[key], true)

        startActivityForResult(intent, id)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQ_PICK_GALLERY) {
                currPath = File(IntentUtils.extraImageFromGallery(requireContext(), data)).absolutePath

                deg[currId]?.let {
                    it.second.invoke(requestCode, it.first)
                }


            } else {
                deg[requestCode]?.let {
                    it.second.invoke(requestCode, it.first)
                }
            }
        }


    }
}